package c2.group.server.schedule;

import c2.advanced.business.base.AdvancedModule;
import c2.group.business.GroupBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;

/** 所有模块共享的时间调度 */
@Slf4j
@Configuration
@EnableScheduling
public class ShareSchedule {

    @Resource
    private ObjectProvider<GroupBody> groupBodyPro;

    @Scheduled(fixedDelay = 1000, initialDelay = 0)
    private void tick() {
        GroupBody body = groupBodyPro.getIfAvailable();
        if(body == null) {
            log.warn("tick过程:GroupBody尚未获取到");
            return;
        }
        for(AdvancedModule module : body.getModules()) {
            long beginTime = System.currentTimeMillis();
            try {
                module.tick();
            } catch (Exception e) {
                log.error("模块[{}]tick时发生异常!", module.getName(), e);
            }
            long costTime = System.currentTimeMillis() - beginTime;
            if(costTime > 300l) {
                log.warn("模块[{}] 高耗时 {} ms", module.getName(), costTime);
            }
        }
    }

    @Scheduled(cron = "0 0 23 ? * SUN")
    private void onSunday2300() {
        GroupBody body = groupBodyPro.getIfAvailable();
        if(body == null) {
            log.error("onSunday2300:GroupBody尚未获取到");
            return;
        }
        log.info("即将执行每周日23:00触发的事件");
    }

    @Scheduled(cron = "1 0 0 * * ?")
    private void onDaySpan() {
        GroupBody body = groupBodyPro.getIfAvailable();
        if (body == null) {
            log.error("onDaySpan:GroupBody尚未获取到");
            return;
        }
        log.info("即将执行跨天的事件");
        try {
            //
        } catch (Exception e) {
            log.error("跨天发生异常",e);
        }
    }
}
